<template>
  <el-drawer
    v-model="renderVisible"
    :title="props.title"
    destroy-on-close
    :size="props.size"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="formRef"
      :label-position="'top'"
      label-width="100px"
      :model="formData"
      :rules="formRules"
    >
      <el-form-item label="帐号" prop="username">
        <el-input
          v-model="formData.username"
          :maxlength="32"
          show-word-limit
          :disabled="props.isEdit"
        ></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="roleId">
        <el-select v-model="formData.roleId">
          <el-option
            v-for="item in roleList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="state" v-if="props.isEdit">
        <el-switch
          v-model="formData.state"
          :active-value="1"
          :inactive-value="0"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <PipeResetBtn :formEl="formRef">重置</PipeResetBtn>
      <el-button
        type="primary"
        @click="handleClickSubmit(formRef)"
        :loading="isLoading"
        >提交</el-button
      >
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { reactive, ref, watch, computed, inject, PropType } from 'vue';
import type { ElForm } from 'element-plus';
import { ElMessage } from 'element-plus';
import { createAccount, updateAccount } from '@/apis/account';
import { loopPropAssignment } from '@/utils/util';

// 加载状态
const isLoading = ref(false);

// 表单ref
const formRef = ref<InstanceType<typeof ElForm>>();

// 表单数据
const formData: API.account.EntityDto = reactive({
  username: '',
  state: 1,
  roleId: 0
});

// 自定义表单验证 - 帐号
const validateUsername = async (_rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入帐号'));
  }

  if (!/^[a-z0-9]*$/g.test(value)) {
    return callback(new Error('帐号只能输入小写字母和数字'));
  }

  callback();
};

const formRules = reactive({
  username: [
    // { type: "string", required: true, message: "请输入登录帐号" }
    { validator: validateUsername, required: true, trigger: 'blur' }
  ],
  roleId: [{ required: true, trigger: 'change', message: '请选择角色' }]
});

// inject
const roleList = inject<Array<{ label: string; value: number }>>('roleList');

// props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },

  title: String,

  size: {
    type: [String, Number],
    default: '30%'
  },

  isEdit: {
    type: Boolean,
    default: false
  },

  rowData: {
    type: Object as PropType<API.account.TableData>,
    default: () => ({})
  }
});

// emits
const emits = defineEmits(['update:modelValue', 'onRefresh']);

// computed - 抽屉[显示|隐藏]
const renderVisible = computed({
  get: () => props.modelValue,
  set: (val) => {
    emits('update:modelValue', val);
  }
});

// watch
watch(
  () => props.modelValue,
  (val) => {
    if (!val) return;
    // 当rowData发生变化，初始化数据
    loopPropAssignment(formData, props.rowData);
  },
  {
    immediate: true
  }
);

// btn - submit
const handleClickSubmit = (formEl: InstanceType<typeof ElForm> | undefined) => {
  if (!formEl) return;

  formEl.validate(async (valid) => {
    if (!valid) return;
    if (props.isEdit) {
      submitDataUpdate(props.rowData.id);
    } else {
      submitDataAdd();
    }
  });
};

// submit - add
const submitDataAdd = () => {
  isLoading.value = true;
  createAccount(formData)
    .then((res) => {
      isLoading.value = false;
      ElMessage.success(res.message);
      // 关闭弹窗
      emits('onRefresh');
      renderVisible.value = false;
    })
    .catch(() => {
      isLoading.value = false;
    });
};

// submit - update
const submitDataUpdate = (id: number) => {
  isLoading.value = true;
  updateAccount(id, formData)
    .then((res) => {
      isLoading.value = false;
      ElMessage.success(res.message);
      // 关闭弹窗
      emits('onRefresh');
      renderVisible.value = false;
    })
    .catch(() => {
      isLoading.value = false;
    });
};
</script>

<style lang="scss" scoped></style>
